// ==UserScript==
// @name         ecs - 公式追踪测试
// @namespace    http://tako.tampermonkey.net/
// @version      0.1
// @description  execRule
// @author       tako
// @match        *://*/*
// @run-at       context-menu
// @grant        none
// @require      https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
// ==/UserScript==
(function () {
  'use strict';
  // Your code here...
  var token = localStorage.getItem('console_TOKEN');
  // console.log(token);

  execRule();

  function execRule() {
    var xhr = new XMLHttpRequest();
    var uri = '/bff/forms-v2/execRule';
    var longUri = '/mdd' + uri;
    var requestTime = Date.now();
    xhr.open('POST', longUri, true);
    xhr.setRequestHeader('timestamp', requestTime);
    xhr.setRequestHeader('Logintoken', token);
    xhr.setRequestHeader('appid', 'c76ef194385e11eb9f43c90043244155');
    xhr.setRequestHeader('accept', 'application/json, text/plain, */*');
    xhr.setRequestHeader('content-type', 'application/json;charset=UTF-8');
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        console.log(data);
      }
    }
    var param = JSON.parse(prompt('请输入参数:', ''));
    var stid = getShaEncodeStr(uri, requestTime, token, param);
    xhr.setRequestHeader('stid', stid);
    xhr.send(JSON.stringify(param));
  }

  function getShaEncodeStr(uri, requestTime, token, param) {
    var paramSign = JSON.stringify(param).replace(/[^a-zA-Z0-9]/g, '');
    var needMdSbd = uri + requestTime + token + paramSign;
    var stid = generateSHA256(needMdSbd);
    return stid;
  }

  // 使用 CryptoJS 生成 SHA-256 哈希
  function generateSHA256(message) {
    const hash = CryptoJS.SHA256(message).toString(CryptoJS.enc.Hex);
    return hash;
  }

})();